<template>
	<view class="zy_content">
		<view ref="column" id="zy_column_view" v-for="(item,index) in contentlist" :key="index" class="zy_list" >
			<!-- 投票  右列第一个元素-->
			<view class="" v-if="index === 0 && voteFlag" style="">
				<minVote :topicId="topicId" v-if="voteShowFlag" @pSelectVote="pSelectVote" :vote="voteData"></minVote>
			</view>


			<!-- 没有投票的情况 -->
			<view v-for="(citem,cindex) in item.list" :key="cindex" class="zy_card" @click="gotoMarketDetail(citem)">
				<view class="" style="position: relative;display: flex;align-items: flex-end;">
					<image @load="showcontent" :data-id="citem.id" :src="citem.coverImage" :key="cindex"
						mode="widthFix">
					</image>
					<view
						style="margin-bottom: 10px;position: absolute;background: black;color: white;font-size: 30rpx;font-weight: 900;margin-left: 6px;padding-right: 7px;border-radius: 5px;">
						￥{{citem.price}}</view>

				</view>

				<view @tap="touch_card" :data-id="citem.id" class="zy_bottom_view">

					<text class="zy_title">{{citem.content}}</text>


					<view class="demo-shop"
						style="display: flex;justify-content: flex-start;align-items: center;margin-left: 5%;margin-top: 10rpx;">
						<img :src="citem.photoUrl" alt="" style="width: 20px;height: 20px;border-radius: 20px;">
						<p style="margin-left: 5px;color: #ccc;font-size: 20rpx;">{{citem.nickName}} </p>
					</view>
				</view>
			</view>
			<!-- 左列热点 -->
			<view
				style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;margin-top: 10px;border-radius: 20px;background-color: #f9f9f9;padding: 10px 10px 0 10px;"
				class="" v-if="index ===0 && rightFlag && hotShowFlag" :style="{height: adjustedHeight}">
				<view class="" style="color: #ccc;">
					相关热点
				</view>

				<view v-for="(item,index) in relativeTopic" :key="item.id" class=""
					style="display: flex;align-items: center;float: left;margin-top: 4px;">
					<img style="width: 20px;height: 20px;" src="@/static/ali/qiqiu.png" alt="" />
					<span style="font-size: 30rpx;font-weight: 1000;">{{item.title}}</span>

				</view>
			</view>
			<!-- 右列热点 -->
			<view
				style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;margin-top: 6px;border-radius: 20px;background-color: #f9f9f9;padding: 3px 6px 0 6px;"
				class="" v-if="index ===1 && leftFlag && hotShowFlag" :style="{ height: adjustedHeight}">
				<view class="" style="color: #ccc;">
					相关热点
				</view>

				<view v-for="(item,index) in relativeTopic" :key="item.id" class=""
					style="display: flex;align-items: center;float: left;margin-top: 4px;">
					<img style="width: 20px;height: 20px;" src="@/static/ali/qiqiu.png" alt="" />
					<span style="font-size: 30rpx;font-weight: 1000;">{{item.title}}</span>

				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import minVote from '@/components/min-vote/vote.vue'
	export default {
		props: {
			flowlist: {
				type: Array
			},
			topicId: {
				type: Number
			}
		},
		data() {
			return {
				//渲染内容列表 (左右两列)
				contentlist: [{
						list: []
					},
					{
						list: []
					}
				],
				chaheight: 0,
				leftFlag: false,
				rightFlag: false,
				voteFlag: false,
				voteData: {},
				voteShowFlag: true, //重新渲染dom的标记
				voteSelectedFlag: false,
				hotShowFlag: true,
				relativeTopic: [],
				count: 0, //请求获取的相关热点数量
				filterList: [],
				minAspectRatioItem: {},
				contentQueue: [],
			};
		},
		computed: {
			adjustedHeight() {
				// 假设 chaheight 已经是一个响应式数据，且其值是不包含 'px' 的纯数字
				// 减去 20rpx。注意，这里直接操作数字，最终结果需要转换为字符串并添加单位
				const height = this.chaheight - 10; // 假设 chaheight 是以 px 为单位的值
				if (height > 40) {
					this.hotShowFlag = true
				} else {
					this.hotShowFlag = false
				}

				return `${height}px`; // 转换为字符串并加上 'px' 单位
			}
		},
		components: {
			minVote
		},
		methods: {
			//用于处理渲染列表的任务队列，保证渲染时顺序执行
			processQueue() {
				if (this.contentQueue.length === 0) {
					return;
				}

				const task = this.contentQueue.shift(); // 获取并移除第一个任务
				task().then(() => {

					if (this.contentQueue.length > 0) {
						this.processQueue(); // 递归处理下一个任务
					}
				});
			},
			showcontent() {
				const task = () => new Promise((resolve, reject) => {
					const index = this.contentlist.reduce((total, current) => total + current.list.length, 0);
					if (index > this.flowlist.length - 1) {
						this.$emit('flowend');
						resolve();
						return;
					}

					const query = uni.createSelectorQuery().in(this);
					query.selectAll('#zy_column_view').boundingClientRect(data => {
						let flag = 0;
						if (data && data.length > 1) {
							flag = data[0].bottom - data[1].bottom < 0 ? 0 : 1;
						}

						if (!this.voteFlag) {
							this.contentlist[flag].list.push(this.flowlist[index]);
						}

						resolve();
					}).exec();

					// 如果有投票
					if (this.voteFlag) {
						// 处理投票元素的高度选择，需要筛选出高度最小的元素放入投票的下面
						this.handleVote();
					}
				});

				this.contentQueue.push(task); // 将任务加入队列

				if (this.contentQueue.length === 1) {
					this.processQueue(); // 如果队列中只有这一个任务，立即处理
				}
			},
			async handleVote() {
				if (this.voteFlag) {


					await this.computeImageHeight(this.flowlist)
					if (this.minAspectRatioItem) {
						this.contentlist[0].list.push(this.minAspectRatioItem);
						this.contentlist[1].list.push(...this.filterList);


					}


					this.computeRelativeTopic();


				}
			},
			//找出最适合放在投票下面的图片,,也就是高度最小的图片
			async computeImageHeight(list) {
				try {
					// 创建一个 Promise 数组来存储所有图片信息获取的异步操作
					let promises = list.map(item => {
						return new Promise((resolve, reject) => {
							uni.getImageInfo({
								src: item.coverImage,
								success: function(image) {
									// 计算高宽比并返回该item及其高宽比
									let aspectRatio = image.height / image.width;
									resolve({
										...item,
										aspectRatio: aspectRatio // 这里保留了item的所有信息，并添加了aspectRatio
									});
								},
								fail: reject // 如果获取信息失败，则reject
							});
						});
					});

					// 等待所有图片信息的 Promise 解决
					let results = await Promise.all(promises);
					// 按照高宽比排序，升序
					results.sort((a, b) => a.aspectRatio - b.aspectRatio);
					// 获取最小高宽比的图片信息，并保存
					this.minAspectRatioItem = results[0];

					// 过滤掉最小高宽比元素的 flowlist
					this.filterList = list.filter(item => item.coverImage !== this.minAspectRatioItem
						.coverImage);

				} catch (error) {
					console.error("获取图片信息失败：", error);
				}
			},
			//卡片点击事件
			touch_card(e) {
				this.$emit('flowtap', e.currentTarget.dataset.id)
			},
			//初始化
			zyinit() {
				this.contentlist = [{
					list: []
				}, {
					list: []
				}];

				this.showcontent();




			},
			pSelectVote(voteItem) {

				this.voteData.vtList.forEach(item => {
					if (item.title === voteItem.title && !this.voteSelectedFlag) {
						this.voteSelectedFlag = true
						item.selected = true
						//重新渲染dom
						this.voteShowFlag = false
					}
				});

				this.voteShowFlag = true

			},

			//计算相关热点
			computeRelativeTopic() {
				setTimeout(() => {
					//计算左右列高度，以进行选择放入
					const query = uni.createSelectorQuery().in(this);
					query.selectAll('#zy_column_view').boundingClientRect(data => {

						this.chaheight = Math.abs(data[0].bottom - data[1].bottom)
						if (data[0].bottom - data[1].bottom < 0) {
							this.rightFlag = true
						} else {
							this.leftFlag = true
						}
						//存放热点的盒子高度值
						const boxHeight = this.chaheight - 37
						//每一条热点的高度为21，计算出可以放入几条
						this.count = boxHeight / 21


						this.$nextTick(() => {

							setTimeout(() => {
								this.getRelativeTopic(this.count);
							}, 0);
						});
					}).exec();
				}, 2000);

			},

			//发送请求获取相关热点
			async getRelativeTopic(count) {

				let form = {
					topicId: this.topicId,
					count: count
				}

				let result = await this.$u.api.getRelativeTopic(form)
				this.relativeTopic = result
				this.$emit("getRelativeTopic",result)

			},
			// 发送vote请求
			async getVoteData() {
				let form = {
					topicId: this.topicId
				}
				let result = await this.$u.api.getVote(form);
				this.voteData = {
					title: result.title,
					nums: result.participateCount,
					vtList: [{
							title: result.content1,
							percent: result.percentage1
						},
						{
							title: result.content2,
							percent: result.percentage2
						},
						{
							title: result.content3,
							percent: result.percentage3
						},
						{
							title: result.content4,
							percent: result.percentage4
						},
						{
							title: result.content5,
							percent: result.percentage5
						},
						{
							title: result.content6,
							percent: result.percentage6
						}
					].filter(item => item.title !== null)

				};

			},
			gotoMarketDetail(item){
				//触发父组件事件,去详情页,带上点击的sku信息
				this.$emit("gotoMarketDetail",item)
			}
		},
		mounted() {
			// 使用自执行的异步函数来处理异步流程
			(async () => {
				if (this.flowlist.length) {
					if (this.flowlist.length === 3) {
						// 等待getVoteData完成
						await this.getVoteData().then(() => {
							this.voteData.vtList.forEach(item => {
								item.selected = false; // 添加默认的 selected 字段
							});

							this.voteFlag = true;
						});
					}

					// 由于是在async函数内，所以这里会等待上面的异步操作完成后才执行
					this.zyinit();

					// 如果没有vote，则计算相关热点元素高度，如果有，则手动触发计算
					if (!this.voteFlag) {


						this.computeRelativeTopic();


					}
				}
			})();
		},


	}
</script>

<style>
	.zy_content {
		width: 100%;
		height: 100%;

		position: relative;
		display: flex;
		flex-direction: row-reverse;
		justify-content: space-evenly;
		align-items: flex-start;
		box-sizing: border-box;

	}

	.zy_list {
		width: 45%;
		display: flex;
		flex-direction: column;

	}

	.zy_card {
		width: 100%;
		background-color: #fefefe;
		border-radius: 10rpx;
		overflow: hidden;
		box-shadow: 1px 1px 5px gray;
		margin-top: 10px;
	}

	.zy_card image {
		width: 100%;
		margin-bottom: 5rpx;
	}

	/* 底部卡片内容 */
	.zy_bottom_view {
		width: 100%;
		min-height: 100rpx;
		background-color: #fff;
		margin-bottom: 15rpx;
	}

	.zy_title {
		display: inline-block;
		width: 90%;
		max-height: 70rpx;
		margin-left: 5%;
		margin-top: 10rpx;
		font-size: 22rpx;

		color: #252525;
		overflow: hidden;
		/* text-overflow: ellipsis; */
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}


	.zy_type_view {
		display: inline-block;
		background-color: #fff3f3;
		margin-bottom: 10rpx;
		color: #e36161;
		font-size: 18rpx;
		padding: 2rpx 5px;
		border-radius: 0 5rpx;
		margin-left: 5%;
	}
</style>